<template>
    <div class="i-table-no-border">
        <Button type="primary" icon="md-add" @click="handleOpenCreate">新建</Button>
        <Table size="small" ref="table" :columns="columns" :data="list" :loading="loading" class="ivu-mt">
            <template slot-scope="{ row }" slot="status">
                <Button type="success" size="small" v-if="row.status === '1'" @click="handlechangeType(row.id, 0)">启用</Button>
                <Button type="error" size="small" v-if="row.status === '0'" @click="handlechangeType(row.id, 1)">禁用</Button>
            </template>
            <template slot-scope="{ row, index }" slot="action">
                    <a @click="handleUpdate(index)">编辑</a>
            </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
            <Page
                    :total="total"
                    :current.sync="current"
                    show-total
                    show-elevator
                    :page-size="size"
                    @on-change="handleChangeSize"
                    :page-size-opts="pageOpts"
                    show-sizer transfer
                    @on-page-size-change="changePageSize"
            />
        </div>
<!--        <div class="ivu-mt ivu-text-center">-->
<!--            <Page :total="total" :current.sync="current" @on-change="handleChangeSize" />-->
<!--        </div>-->
        <Modal v-model="showCreate" :title="title" :mask-closable= "false" draggable :loading="creating" @on-ok="handleCreate">
            <Form ref="create" :model="createMenuData" :rules="createRules" :label-width="100">
                <FormItem label="菜单名称：" prop="name">
                    <Input v-model="createMenuData.name" placeholder="请输入菜单名称" clearable/>
                </FormItem>
                <FormItem label="所属模块：" prop="module_id">
                    <Select v-model="createMenuData.module_id" placeholder="请选择所属模块" @on-change="changemodule">
                        <Option v-for="item in modulelist" :key="item.id" :value="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="父菜单名称：" prop="parent_menu_id" v-if="createMenuData.module_id!==''&&parentMenuLists&&parentMenuLists.length>0">
                    <TreeSelect v-model="createMenuData.parent_menu_id" :data="parentMenuLists" v-width="200" clearable/>
                </FormItem>
                <FormItem label="菜单链接：" prop="url">
                    <Input v-model="createMenuData.url" placeholder="请输入菜单链接" clearable/>
                </FormItem>
                <FormItem label="菜单Icon：" prop="class_style">
                    <Input v-model="createMenuData.class_style" placeholder="请输入Icon类名" clearable/>
                </FormItem>
                <FormItem label="排序：" prop="sort">
                    <Input v-model="createMenuData.sort" placeholder="请输入排序大小" />
                </FormItem>
                <FormItem label="菜单状态：">
                    <Switch v-model="createMenuData.status" size="large">
                        <span slot="open">开启</span>
                        <span slot="close">关闭</span>
                    </Switch>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
    import {
        GetMenus,
        GetParentMenus,
        CreateMenu,
        UpdateMenu,
        ChangeTypeMenu
    } from '@/api/setting';

    export default {
        data () {
            return {
                columns: [
                    {
                        title: '菜单名称',
                        key: 'name',
                        minWidth: 100
                    },
                    {
                        title: '所属模块',
                        key: 'module_name',
                        minWidth: 100
                    },
                    {
                        title: '父菜单名称',
                        key: 'pname',
                        minWidth: 100
                    },
                    {
                        title: '菜单Icon',
                        key: 'class_style',
                        minWidth: 160
                    },
                    {
                        title: 'url路径',
                        key: 'url',
                        minWidth: 140
                    },
                    {
                        title: '排序',
                        key: 'sort',
                        minWidth: 50
                    },
                    {
                        title: '状态',
                        slot: 'status',
                        minWidth: 60
                    },
                    {
                        title: '创建时间',
                        key: 'created_at_str',
                        minWidth: 140
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        align: 'center',
                        minWidth: 80
                    }
                ],
                loading: false,
                list: [],
                pageOpts: [10, 20, 30, 50],
                moduleList: [],
                modulelist: [],
                parentMenuList: {},
                parentMenuLists: [],
                current: 1,
                size: 10,
                total: 0,
                showCreate: false,
                createMenuData: {
                    name: '',
                    module_id: '',
                    url: '',
                    parent_menu_id: '',
                    class_style: '',
                    status: true,
                    sort: ''
                },
                createRules: {
                    name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
                    module_id: [{ required: true, message: '请选择所属模块', trigger: 'change' }],
                    url: [{ required: true, message: '请输入菜单连接', trigger: 'blur' }],
                    class_style: [
                        { required: true, message: '请输入菜单Icon', trigger: 'blur' }
                    ],
                    sort: [
                        {
                            message: '排序必须是正数',
                            pattern: /^[+]{0,1}(\d+)$/,
                            trigger: 'blur'
                        }
                    ],
                    module_id: [{ required: true, message: '请选择模块', trigger: 'blur' }],
                    status: [{ required: true, message: '请输入菜单状态', trigger: 'blur' }]
                },
                creating: true,
                updateIndex: -1,
                editing: true,
                title: '新增'
            };
        },
        methods: {
            getData () {
                this.loading = true;
                GetMenus({
                    pageSize: this.size,
                    page: this.current
                }).then(res => {
                    this.list = res.list;
                    this.total = res.total;
                }).finally(() => {
                    this.loading = false;
                })
            },
            // 获取父级菜单
            getParentMenuList (moduleId, menu) {
                GetParentMenus({ id: moduleId }).then(res => {
                    this.parentMenuList = res.menu_list;
                    this.modulelist = res.module_list
                    if (menu) {
                        this.changemodule(menu)
                    }
                });
            },
            handleSelectModule (value) {
                // 选中模块
                if (!value) return false;
                this.getParentMenuList(value);
            },
            // 点击切换分页
            handleChangeSize (currentPage) {
                this.current = currentPage;
                this.getData();
            },
            changePageSize (e) {
                this.size = e
                this.getData()
            },
            // 切换状态
            handlechangeType (id, type) {
                this.$Modal.confirm({
                    title: '警告',
                    content: '是否确认' + (type === 1 ? '开启' : '关闭') + '该菜单？',
                    onOk: () => {
                        ChangeTypeMenu({
                            id: id,
                            status: type
                        }).then(() => {
                            this.getData();
                            this.$Message.success('修改成功');
                        });
                    }
                });
            },
            // 点击新增
            handleOpenCreate () {
                this.updateIndex = -1;
                this.showCreate = true;
                this.title = '新增';
                this.$nextTick(() => {
                    this.$refs['create'].resetFields();
                });
                this.getParentMenuList(0);
            },
            // 新增数据
            handleCreate () {
                this.$refs.create.validate(valid => {
                    if (valid) {
                        let sendData = JSON.parse(JSON.stringify(this.createMenuData));
                        sendData.status = sendData.status === true ? '1' : '0';
                        if (this.updateIndex < 0) {
                            // 新建
                            CreateMenu(sendData).then(res => {
                                // 创建模块成功后，刷新页面
                                this.showCreate = false;
                                this.getData();
                                this.$Message.success('创建菜单成功');
                            });
                        } else {
                            // 修改
                            UpdateMenu(sendData).then(res => {
                                // 修改模块成功后，刷新页面
                                this.showCreate = false;
                                this.getData();
                                this.$Message.success('修改成功');
                            });
                        }
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    } else {
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    }
                });
            },
            // 编辑数据
            handleUpdate (index) {
                this.showCreate = true;
                this.title = '编辑';
                this.$nextTick(() => {
                    this.$refs['create'].resetFields();
                    this.updateIndex = index;
                    const item = this.list[index];
                    for (let key in this.createMenuData) {
                        this.createMenuData[key] = item[key];
                    }
                    this.createMenuData.status = this.createMenuData.status === '1';
                    this.createMenuData.id = item.id;
                    this.getParentMenuList(item.id, this.createMenuData.module_id);
                });
            },
            changemodule (e) {
                this.parentMenuLists = this.parentMenuList[`${e}`]
            }
        }
    };
</script>
